// initial state
const state = {
    // 购物车商品集合
    items: [], // 所存方式 { good:data, num:111 }
    checkoutStatus: false // 该商品是否已在购物车
}

// getters
const getters = {
    // 获取购物车所有商品
    cartProducts(state) {
        return state.items;
    },
    // 获取购物车所有商品总价
    cartTotalPrice(state) {

    },
    // 总商品数
    cartTotalNum(state) {
        let sum = 0;
        for (let i = 0; i < state.items.length; i++) {
            sum += state.items[i].num;
        }
        return sum;
    },
    // 总商品数
    cartTotalNum_view(state) {
        let sum = 0;
        for (let i = 0; i < state.items.length; i++) {
            sum += state.items[i].num;
        }
        return sum > 99 ? '99+' : sum;
    },
    // 获取购物车中具体某个商品的数量
    cartGoodNum: (state, getters) => (id) => {
        for ( let i = 0; i<state.items.length; i++ ){
            if( state.items[i].good.id === id ){
                return state.items[i].num
            }
        }
        return 0
    },
    // 获取商品总价
    cartGoodSum(state){
        var sum = 0;
        for( var i = 0; i<state.items.length; i++ ){
            sum += state.items[i].num * state.items[i].good.price
        }
        return sum
    }


    
}

// actions
const actions = {
    // 添加购物车商品
    addProductToCart(state, obj) {
        state.commit('checkout_Product_is_in_cart', obj);
        state.commit('addProductToCart', obj);
    },
    // 减少商品数
    minusProductToCart(state, goodid) {
        state.commit('minusProductToCart',goodid);
    },
    // 清空购物车
    emptyCart(state) {

    }
}

// mutations
const mutations = {
    addProductToCart(state, obj) {
        if (state.checkoutStatus) {
            for (let i = 0; i < state.items.length; i++) {
                if (state.items[i].good.id === obj.id) {
                    state.items[i].num = (state.items[i].num - 0) + 1;
                    return;
                }
            }
        } else {
            let item = {
                good: obj,
                num: 1
            };
            state.items.push(item);
        }
    },
    // 减少商品数
    minusProductToCart(state, goodid) {
        for(let i=0; i<state.items.length; i++){
            if(state.items[i].good.id === goodid){
                state.items[i].num = state.items[i].num - 1;
                if(state.items[i].num < 1){
                    state.items.splice(i,1)
                }
            }
        }
    },
    // 检索商品状态
    checkout_Product_is_in_cart(state, obj) {
        for (let i = 0; i < state.items.length; i++) {
            if (state.items[i].good.id === obj.id) {
                return state.checkoutStatus = true
            }
        }
        state.checkoutStatus = false;
    },
    // 清空购物车
    emptyCart(state) {

    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}